<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use DB;

class BaseModel extends Model
{

    /**
     * 获取模型表名
     * table
     *
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function scopeTable($query)
    {
        return $query->getModel()->getTable();
    }

    /**
     * 设置模型别名
     * alias
     *
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function scopeAlias($query,$alias)
    {
        return $query->getModel()->setTable($query->getModel()->getTable().' as '.$alias);
    }

    /**
     * 字段为null或空字符串
     * whereEmpty
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function scopeWhereEmpty($query, $column)
    {
        return $query->where(function ($query) use ($column){
            $query->whereNull($column)
                ->orWhere($column,'');
        });
    }

    /**
     * 字段不为null或空字符串
     * whereNotEmpty
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function scopeWhereNotEmpty($query, $column)
    {
        return $query->where(function ($query) use ($column){
            $query->whereNotNull($column)
                ->where($column,'<>','');
        });
    }

    /**
     * 获取sql语句而不丢失查询条件
     * @param $query
     * @return mixed
     */
//    public function scopeSql($query)
//    {
//        return (clone $query)->toSql();
//    }

    /**
     * 启用请求日志
     * @param $query
     */
    public function scopeEnableQueryLog($query)
    {
        DB::enableQueryLog();
    }

    /**
     * 获取最后一条sql日志
     * @param $query
     * @return array
     */
    public function scopeGetQueryLog($query)
    {
        return DB::getQueryLog();
    }

}
